#!/usr/local/bin/perl

package Armory::Item;
use strict;

use LWP::UserAgent;
use XML::Simple;
use Data::Dumper;

my %slotname = (
	1 => 'head',
	2 => 'neck',
	3 => 'shoulder',
	4 => 'shirt',
	5 => 'chest',
	6 => 'belt',
	7 => 'legs',
	8 => 'feet',
	9 => 'wrist',
	10 => 'gloves',
	11 => 'finger',
	12 => 'trinket',
	13 => 'one hand',
	14 => 'shield',
	16 => 'back',
	17 => 'two hand',
	19 => 'tabard',
	22 => 'off hand',
	23 => 'off hand frill',
	24 => 'ammo',
	26 => 'ranged',
);

my %qualname = (
	0 => 'poor',
	1 => 'common',
	2 => 'uncommon',
	3 => 'rare',
	4 => 'epic',
	5 => 'legendary',
);

sub new {
	my ($perlclass, %conf) = @_;
	my $self  = {};
	$self->{ID}       = $conf{'id'} || undef;
	$self->{REALM}    = $conf{'realm'} || undef;
	$self->{CHARNAME} = $conf{'charname'} || undef;
	bless($self, $perlclass);
	return $self;
}

sub id {
	my $self = shift;
	if (@_) { $self->{ID} = shift }
	return $self->{ID};
}

sub realm {
	my $self = shift;
	if (@_) { $self->{REALM} = shift }
	return $self->{REALM};
}

sub charname {
	my $self = shift;
	if (@_) { $self->{CHARNAME} = shift }
	return $self->{CHARNAME};
}

sub name {
	my $self = shift;
	return $self->{NAME};
}

sub enchant {
	my $self = shift;
	return $self->{ENCHANT};
}

sub slot {
	my $self = shift;
	return $self->{SLOT};
}

sub slotname {
	my $self = shift;
	return $self->{SLOTNAME};
}

sub quality {
	my $self = shift;
	return $self->{QUALITY};
}

sub qualityname {
	my $self = shift;
	return $self->{QUALITYNAME};
}

sub type {
	my $self = shift;
	return $self->{TYPE};
}

sub fetch {
	my $self = shift;
	if (@_) {
		my %conf = @_;
		$self->{ID} = $conf{'id'} || $self->{ID};
		$self->{CHARNAME} = $conf{'charname'} || $self->{CHARNAME};
		$self->{REALM} = $conf{'realm'} || $self->{REALM};
	}

	if (! $self->{ID}) {
		return 0;
	}

	my $baseurl = "http://armory.worldofwarcraft.com/item-tooltip.xml";

	my $ua = LWP::UserAgent->new( 'agent' => 'Firefox/2.0' );
	my $response = $ua->get($baseurl . '?i=' . $self->{ID} . '&n=' . $self->{CHARNAME} . '&r=' . $self->{REALM});

	if (! $response->is_success) {
		return 0;
	}

	my $ref = XMLin($response->content);

	my $iteminfo = $ref->{'itemTooltips'}->{'itemTooltip'};
	$self->{NAME} = $iteminfo->{'name'};
	$self->{ENCHANT} = $iteminfo->{'enchant'} || "";
	$self->{SLOT} = $iteminfo->{'equipData'}->{'inventoryType'};
	$self->{SLOTNAME} = $slotname{$self->{SLOT}};
	$self->{QUALITY} = $iteminfo->{'overallQualityId'};
	$self->{QUALITYNAME} = $qualname{$self->{QUALITY}};
	$self->{TYPE} = $iteminfo->{'equipData'}->{'subclassName'};

	return 1;
}

1;


